package com.example.studyes.print;

import com.alibaba.fastjson.JSONObject;
import com.example.studyes.conf.ElasticSearchConfiguration;
import com.example.studyes.entity.UserDO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hanll
 * @ClassName: Print
 * @Date: 2022-12-16 10:30
 * @Version: 1.0
 * @Description:
 */
public class ElasticSearchTest {

    private RestHighLevelClient esClient = ElasticSearchConfiguration.client();

    /**
     * 创建索引
     */
    @Test
    public void elasticSearchIndex() throws Exception {
        //创建ES客户端
        IndexRequest request = new IndexRequest();
        request.index("test").id("1");
        UserDO userDO = new UserDO("韩亮亮", 21, "男");
        ObjectMapper objectMapper = new ObjectMapper();
        String userJSON = objectMapper.writeValueAsString(userDO);
        request.source(userJSON, XContentType.JSON);
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        esClient.close();
    }

    /**
     * 查询文档
     */
    @Test
    public void elasticSearchGet() throws Exception {
        //创建ES客户端
        GetRequest request = new GetRequest();
        request.index("test").id("1");
        GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsMap());
        esClient.close();
    }

    /**
     * 删除文档
     */
    @Test
    public void elasticSearchDelete() throws Exception {
        //创建ES客户端
        RestHighLevelClient esClient = ElasticSearchConfiguration.client();
        DeleteRequest request = new DeleteRequest();
        request.index("test").id("1");
        DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        esClient.close();
    }

    /**
     * 批量创建文档
     */
    @Test
    public void ElasticSearchBulkDocument() throws Exception {
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("test").id("1").source(XContentType.JSON, "name", "韩亮亮", "age", 21, "sex", "男"));
        request.add(new IndexRequest().index("test").id("2").source(XContentType.JSON, "name", "范胜全", "age", 27, "sex", "男"));
        request.add(new IndexRequest().index("test").id("3").source(XContentType.JSON, "name", "张连伟", "age", 23, "sex", "女"));
        request.add(new IndexRequest().index("test").id("4").source(XContentType.JSON, "name", "夏晴风", "age", 23, "sex", "男"));
        request.add(new IndexRequest().index("test").id("5").source(XContentType.JSON, "name", "叶海波", "age", 24, "sex", "男"));
        request.add(new IndexRequest().index("test").id("6").source(XContentType.JSON, "name", "向海灵", "age", 34, "sex", "男"));
        BulkResponse bulk = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(bulk.getTook());
        esClient.close();
    }

    /**
     * 批量删除文档
     */
    @Test
    public void elasticSearchBulkDelete() throws Exception {
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("test").id("1"));
        request.add(new DeleteRequest().index("test").id("2"));
        request.add(new DeleteRequest().index("test").id("3"));
        BulkResponse bulk = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(bulk.getTook());
        System.out.println(bulk.getItems());
        esClient.close();
    }

    /**
     * 查询全量文档
     */
    @Test
    public void elasticSearchQuery() throws Exception {
        SearchRequest request = new SearchRequest();
        request.indices("test");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //条件查询
        searchSourceBuilder.query(QueryBuilders.termQuery("name","韩亮亮"));
        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(2);
        //排序
        searchSourceBuilder.sort("age", SortOrder.ASC);
        //做全量查询，同时排除性别sex字段。
        String [] excludes = {"sex"};
        String [] includes = {};
        searchSourceBuilder.fetchSource(excludes, includes);
        request.source(searchSourceBuilder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println("长度：" + hits.getTotalHits().value);
        System.out.println("响应时间：" + response.getTook());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        esClient.close();
    }

    /**
     * 监听索引(自创"性能极差")
     */
    @Test
    public void listenerIndex() {
        ((Runnable) () -> {
            while (true) {
                try {
                    Thread.sleep(1000L);
                    SearchRequest request = new SearchRequest();
                    request.indices("test");
                    request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
                    SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
                    SearchHits hits = response.getHits();
                    if (hits.getTotalHits().value <= 0) {
                        continue;
                    }
                    boolean notNull = false;
                    List<Integer> ids = new ArrayList<>();
                    for (SearchHit hit : hits) {
                        UserDO userDO = JSONObject.parseObject(hit.getSourceAsString(), UserDO.class);
                        System.out.println(userDO);
                        ids.add(Integer.parseInt(hit.getId()));
                        notNull = true;
                    }
                    if (notNull) {
                        BulkRequest request1 = new BulkRequest("test");
                        for (Integer id : ids) {
                            request1.add(new DeleteRequest().id(id.toString()));
                        }
                        esClient.bulk(request1, RequestOptions.DEFAULT);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }).run();

    }
}
